#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>

unsigned int BytesToLong(unsigned int a ,unsigned int b ,unsigned int c,unsigned int d) {
    return (unsigned int)a << 24 | (unsigned int)b << 16 | (unsigned int)c << 8 | d;
}

int main() {
    FILE *fp,*fw;
    int ip[4] = {61,135,169,121};
    int ch;
   //load
   if((fp = fopen("./17monipdb.dat","rb")) == NULL) {
       printf("the file can not be opened.\n");
       return 1;
   }
    long fileLength = 0;
    fseek(fp,0,SEEK_SET);
    fseek(fp,0,SEEK_END);
    fileLength = ftell(fp);
    fseek(fp,0,SEEK_SET);
    printf("Load %ld bytes success\n",fileLength);
    ch = fgetc(fp);
    int index = 0;
    char *dataBuffer = (char *)malloc(sizeof(char)*fileLength);
    while(ch != EOF) {
        dataBuffer[index] = ch;
        index++;
        ch = fgetc(fp);
    }
    fclose(fp);
    unsigned int uiIndexLen= 0;
    memcpy(&uiIndexLen,&dataBuffer[0],4);
    uiIndexLen = ntohl(uiIndexLen);
    char *pIPIndex = &dataBuffer[4];
    char *pIPData = &dataBuffer[uiIndexLen];
    
    //find
   unsigned int uiIP = BytesToLong(ip[0],ip[1],ip[2],ip[3]);
   int iFirst = ip[0];
   int iStart = 0;
   memcpy(&iStart,pIPIndex + (iFirst * 4),4);
   int iMaxComLen = pIPData - pIPIndex - 1024 - 4;
   int iIndexOffset = -1;
   unsigned int ucIndexLength = 0;
   for(iStart = iStart * 8 + 1024;iStart < iMaxComLen;iStart += 8) {
       unsigned int uiCurrIP = 0;
       memcpy(&uiCurrIP,pIPIndex+iStart,4);
       uiCurrIP = ntohl(uiCurrIP);
       if(uiCurrIP >= uiIP) {
           iIndexOffset = 0;
           memcpy(&iIndexOffset, pIPIndex+iStart+4, 3);
           memcpy(&ucIndexLength, pIPIndex+iStart+7, 1);
           break;
       }
   }
   if(iIndexOffset == -1) {
       return 1;
   }
   char *area = (char *)malloc(sizeof(char) * ucIndexLength);
   for(int i = 0;i < ucIndexLength;i++) {
       area[i] = pIPData[iIndexOffset - 1024 + i];
   }
   printf("%u.%u.%u.%u ->  %s\n",ip[0],ip[1],ip[2],ip[3],area);
    free(dataBuffer);
    printf("End read file content!\n");
    return 0;
}
